﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO.Packaging;
using System.IO;
using System.Xml;
using VsxFactory.Modeling.VisualStudio;
using System.Xml.Serialization;
using System.Net;
using System.ComponentModel.Composition;
using System.Data.Services.Client;
using System.Reflection;
using System.ComponentModel;
using VsxFactory.Modeling.Strategies;

namespace VsxFactory.Modeling.Repository
{
    [Export(typeof(VsxFactory.Modeling.Repository.IPackageRepository))]
    public class OnlinePackageRepository : VsxFactory.Modeling.Repository.IPackageRepository
    {
        private IStrategyContext _context;
        public PackageSource _source;

        public OnlinePackageRepository(IStrategyContext context, PackageSource source)
        {
            System.Diagnostics.Contracts.Contract.Requires(source != null);
            System.Diagnostics.Contracts.Contract.Requires(context != null);

            _context = context;
            _source = source;
        }

        public PackageSource Source
        {
            get { return _source; }
        }

        /// <summary>
        /// Gets the remote packages list.
        /// </summary>
        /// <param name="address">The address.</param>
        /// <returns></returns>
        public virtual IQueryable<PackageInfo> GetPackages()
        {
            try
            {
                if (String.IsNullOrEmpty( _source.Source ))
                    return Enumerable.Empty<PackageInfo>().AsQueryable();

                var context = new RepositoryDataContext(_source.SourceAsUri);
                DataServiceQuery<PackageInfo> query = context.CreateQuery<PackageInfo>("Packages");
                return query.AsQueryable();
            }
            catch(Exception ex)
            {
                return new List<PackageInfo>() { new PackageInfo() { Kind = PackageKind.Error, Name = "Error", Description = ex.Message } }.AsQueryable();
            }
        }

        public virtual void Uninstall(PackageInfo package)
        {
            string folder = _context.Settings.ResolvePackageFolder(package);
            // Suppression du répertoire contenant l'extraction du package
            Utils.RemoveDirectory(folder);
            // Suppression du package
            Utils.DeleteFile(_context.Settings.ResolvePackageFileName(package));
        }

        /// <summary>
        /// Loads a package.
        /// </summary>
        /// <param name="info">The info.</param>
        /// <returns></returns>
        public virtual void InstallPackage(PackageInfo info)
        {
            throw new NotImplementedException();
        }
    }

}
